<script setup lang="ts">
import { ref, watch, toRefs } from 'vue'
import { ElMessage, FormInstance, UploadFile } from 'element-plus'
import { orderAnnexUpload } from '../../../../../api/upload'
import { saveRemark } from '@/api/order'
import { OrderAPIRequestParam } from './order'
import useFormValidateService from './useFormValidate'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: () => false,
  },
  workIds: {
    type: Array<string>,
    required: true,
  },
})
const { workIds } = toRefs(props)

const emits = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'updated'): void
}>()

/**
 * 使用表单验证服务
 */
const { handleFormValidate, formValidateResult, resetFormValidateResult } =
  useFormValidateService(['note'])

// 表单验证规则
const rules = ref({
  remark: [
    {
      required: true,
      message: '请输入备注',
      trigger: ['blur', 'change'],
    },
  ],
  visitTypes: [
    {
      required: true,
      message: '请选择可见类型',
      trigger: ['blur', 'change'],
    },
  ],
})

// 弹窗状态
const visible = ref(false)

/**
 * 关闭事件
 */
const onClose = () => {
  form.value = {
    "annexs": [],
    "remark": "",
    "visitTypes": [0],
    "workIds": []
  }
  visible.value = false
  resetFormValidateResult()
  emits('update:modelValue', visible.value)
}

// 表单
const form = ref({
  "annexs": [],
  "remark": "",
  "visitTypes": [0],
  "workIds": []
})

/**
 * 移除图片事件
 * @param {object} file - 文件
 */
// const handleRemove = (file: UploadFile) => {
//   const index = form.value.fileList.findIndex((item) => item.url === file.url)
//   form.value.fileList.splice(index, 1)
// }

/**
 * 文件上传
 * @param {object} file - 文件
 */
// const handleChange = (file: UploadFile) => {
//   const fileReader = new FileReader()
//   fileReader.readAsDataURL(file.raw)
//   fileReader.onload = () => {
//     if (form.value.fileList.length + 1 > 5) {
//       ElMessage({
//         type: 'error',
//         message: '最多只能上传5张图片',
//       })
//       return false
//     }
//     form.value.fileList.push(Object.assign(file, { url: fileReader.result }))
//   }
// }

// form组件实例
const formRef = ref<FormInstance | null>(null)

// 保存加载
const saveLoading = ref(false)

/**
 * 确定事件
 */
const onConfirm = () => {
  if (formRef.value) {
    formRef.value.validate(async (valid) => {
      if (valid) {
        saveLoading.value = true
        form.value.workIds = props.workIds


        // for (let i = 0; i < form.value.fileList.length; i++) {
        //   const res = await orderAnnexUpload([form.value.fileList[i].raw])
        //   data.annexs.push(res.data.data.rows[0])
        // }

        const saveResult = await saveRemark(form.value)
        ElMessage({
          type: saveResult.data.success ? 'success' : 'error',
          message: saveResult.data.message,
        })
        if (saveResult.data.success) {
          visible.value = false
          emits('update:modelValue', visible.value)
          form.value = {
            "annexs": [],
            "remark": "",
            "visitTypes": [0],
            "workIds": []
          }
          emits('updated')
        }
        saveLoading.value = false
      }
    })
  }
}

watch(
  () => props.modelValue,
  (value) => {
    visible.value = value
  },
)
</script>

<template>
  <div>
    <el-dialog width="540px" top="8vh" :draggable="true" :destroy-on-close="true" :close-on-click-modal="false"
      :align-center="true" v-model="visible" @close="onClose" title="填写备注">
      <div class="title">
        <span>当前选中</span>
        <span class="num">{{ props.workIds.length }}</span>
        <span>个工单进行批量备注！</span>
      </div>
      <el-form v-loading="saveLoading" ref="formRef" label-width="auto" :rules="rules" :model="form"
        @validate="handleFormValidate" class="modal_form_content">
        <!--工单备注-->
        <el-form-item label="工单备注" prop="remark" class="form_textarea_item">
          <el-input type="textarea" placeholder="请填写备注" v-model="form.remark" maxlength="200" show-word-limit
            resize="both" />
        </el-form-item>

        <!--可见类型-->
        <el-form-item prop="visitTypes" class="form_checkbox_group_item" label="可见类型">
          <el-checkbox-group v-model="form.visitTypes" class="visit_type">
            <el-checkbox :label="0">
              <span class="visit_type_text">公开</span>
            </el-checkbox>
            <el-checkbox :label="1">
              <span class="visit_type_text">服务商可见</span>
            </el-checkbox>
            <el-checkbox :label="2">
              <span class="visit_type_text">工程师可见</span>
            </el-checkbox>
            <el-checkbox :label="3">
              <span class="visit_type_text">客户可见</span>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="onClose" style="width: 60px;" class="btn_cancel"> 取消 </el-button>
        <el-button color="#007cff" style="width: 60px;" :loading="saveLoading" class="btn_save"
          @click="onConfirm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
@import './ServiceProcess.scss';
</style>
